package main

import (
	"fmt"
	"sync"
)

func main() {
	pairs := []struct{
		k string
		v int
	}{
		{"k1", 1},
		{"k2", 2},
		{"k3", 3},
		{"k4", 4},
	}

	{
		fmt.Println("创建map")
		cm := sync.Map{}
		for i := range pairs {
			cm.Store(pairs[i].k, pairs[i].v)
		}

		fmt.Println("遍历输出map")
		cm.Range (func(k, v interface{}) bool {
			fmt.Printf("%v: %v\n", k, v)
			return true
		})

		fmt.Println("Load 和 LoadOrStore 方法")
		key := "k3"
		value, ok := cm.Load(key)
		fmt.Printf("Load %v: %v: %v\n", ok, key, value)
		value, ok = cm.LoadOrStore(key, 5)
		fmt.Printf("LoadOrStore %v: %v: %v\n", ok, key, value)
		key = "k5"
		value, ok = cm.Load(key)
		fmt.Printf("Load %v: %v: %v\n", ok, key, value)
		value, ok = cm.LoadOrStore(key, 5)
		fmt.Printf("LoadOrStore %v: %v: %v\n", ok, key, value)

		fmt.Println("Delete 方法")
		key = "k2"
		cm.Delete(key)
		key = "k21"
		cm.Delete(key)

		fmt.Println("遍历输出map")
		cm.Range (func(k, v interface{}) bool {
			fmt.Printf("%v: %v\n", k, v)
			return true
		})
	}
	fmt.Println("Over")
}